/*
 * @lc app=leetcode.cn id=450 lang=cpp
 *
 * [450] 删除二叉搜索树中的节点
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    TreeNode *getPrecursor(TreeNode *root) {
        TreeNode *node = root->left;
        while (node->right != NULL) {
            node = node->right;
        }
        return node;
    }
    TreeNode *deleteNode(TreeNode *root, int key) {
        if (root == NULL) {
            return root;
        }
        if (key > root->val) {
            root->right = deleteNode(root->right, key);
        } else if (key < root->val) {
            root->left = deleteNode(root->left, key);
        } else {
            if (root->left == NULL || root->right == NULL) {
                TreeNode *temp = root->left ? root->left : root->right;
                return temp;
            } else {
                TreeNode *temp = getPrecursor(root);
                root->val = temp->val;
                root->left = deleteNode(root->left, temp->val);
            }
        }
        return root;
    }
};
// @lc code=end
